﻿using System;
using System.Web.Mvc;
using Core.Model;
using Core.Services;
using Infrastructure.Repositories;
using UI.Infrastructure.ShoppingCart;
using UI.Models.ShoppingCart;

namespace UI.Controllers
{
    public class ShoppingCartController : Controller
    {
        private readonly ICartRepository _cartRepository;
        private readonly ICatalogService _catalogService;

        public ShoppingCartController()
            : this(new CartRepository(), new CatalogService(new CatalogRepository()))
        {
        }

        public ShoppingCartController(ICartRepository cartRepository, ICatalogService catalogService)
        {
            if (cartRepository == null) throw new ArgumentNullException("cartRepository");
            if (catalogService == null) throw new ArgumentNullException("catalogService");
            _cartRepository = cartRepository;
            _catalogService = catalogService;
        }

        [AllowAnonymous]
        public ActionResult Index()
        {
            Cart cart = _cartRepository.GetCart();

            if (cart.CartItems.Count > 0)
            {
                return View(cart);
            }
            return View("Empty");
        }

        [AllowAnonymous]
        public ActionResult AddItem(string itemId)
        {
            Item item = _catalogService.GetItemDetails(itemId);
            if (item == null) return RedirectToAction("ItemNotFound", "Catalog");


            CartItem cartItem = new CartItemFactory().CreateFrom(item);
            cartItem.Quantity = 1;

            Cart cart = _cartRepository.GetCart();

            cart.AddCartItem(cartItem);


            return RedirectToAction("Index", "ShoppingCart");
        }

        [AllowAnonymous]
        public ActionResult RemoveItem(string itemId)
        {
            Cart cart = _cartRepository.GetCart();
            cart.RemoveCartItem(itemId);
            return RedirectToAction("Index", "ShoppingCart");
        }
    }
}